package com.java.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 有关java.util.Date和java.sql.Date方法的收录
 * @author Administrator
 *
 */
public class TimeTest {

	// Str to Date(yyyy-MM-dd)
	private static SimpleDateFormat mf = new SimpleDateFormat("yyyy-MM-dd");
	
	public static void main(String[] args) {
		System.out.println("1.两个日期之间的间隔天数  --- " + getBetweenAnd("2012-02-01","2012-03-21"));
		System.out.println("2.返回日期是星期几 --- " + getWeek("2012-06-11"));
		System.out.println("3.返回本月的最后一天 --- " + getMonthLastDay());
		System.out.println("4.返回上月的第一天 --- " + getBeforMonthFirstDay());
		System.out.println("5.获取今天和本周日相差的天数 --- " + getCurDifSun());
		System.out.println("6.返回本周日的日期 --- " + getCurrentWeekDay());
	}
	
	// 获取两个日期的间隔天数
	public static String getBetweenAnd(String startStr, String endStr){
		long day = 0;
		try {
			Date startdate = mf.parse(startStr);
			Date enddate = mf.parse(endStr);
			day = (enddate.getTime() - startdate.getTime())/(3600*24*1000);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return day + "";
	}
	
	// 根据日期返回星期几
	@SuppressWarnings("static-access")
	public static String getWeek(String dateStr){
		Date date = null;
		Calendar c = Calendar.getInstance();
		try {
			date = mf.parse(dateStr);
			c = Calendar.getInstance();
			c.setTime(date);
			// week 中存的就是星期几了，1~7:1=星期日,7=星期六,其他类推
			int week = c.DAY_OF_WEEK;
			//System.out.println(week);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return new SimpleDateFormat("EEEE").format(c.getTime());
	}

	//获取本月最后一天
	public static String getMonthLastDay(){
		Calendar c = Calendar.getInstance();
		// 设为本月的第一天
		c.set(Calendar.DATE, 1);
		// 加一个月，变为下月的第一天
		c.add(Calendar.MONTH, 1);
		// 减一天，即为本月的最后一天
		c.add(Calendar.DATE, -1);
		String str = mf.format(c.getTime());
		return str;
	}
	
	// 获取上月的第一天
	public static String getBeforMonthFirstDay(){
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DATE, 1);
		// 月份减一,即为上月第一天
		c.add(Calendar.MONTH, -1);
		String str = mf.format(c.getTime());
		return str;
	}
	
	// 获得当前日期与本周日相差的天数    
	public static Integer getCurDifSun(){
		Calendar c = Calendar.getInstance();
		// 计算今天是一周的第几天
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
		if(dayOfWeek == 0){
			return 0;
		} else {
			return 7 - dayOfWeek;
		}
	}
	
	// 获取本周星期日的日期
	public static String getCurrentWeekDay(){
		// 获取今天和周日差了几天
		int dayOfWeek = getCurDifSun();
		Calendar calendar = Calendar.getInstance();
		calendar.add(GregorianCalendar.DATE, dayOfWeek);
		Date date = calendar.getTime();
		String dateStr = mf.format(date);
		return dateStr;
	}
}
